package com.mgq.algorithm.link;

import com.mgq.algorithm.twotree.TreeNode;

/**
 * @author MaGuangQi
 * 从前序与中序遍历序列构造二叉树
 * @date 2022-02-18 16:00
 **/
public class PreorderAndInorder_105 {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return build(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    }

    public TreeNode build(int[] preorder, int preStart, int preEnd,
                          int[] inorder, int inStart, int inEnd) {
        if (preStart > preEnd) return null;
        //先确定根节点,先序遍历的第一个节点就是根.
        int rootVal = preorder[preStart];
        TreeNode root = new TreeNode(rootVal);
        //根据root节点,找到中序遍历中的位置
        int index = -1;
        for (int i = inStart; i <= inEnd; i++) {
            if (inorder[i] == root.val) {
                index = i;
                break;
            }
        }
        //难点是如何确定先序遍历的index, 可以根据中序遍历的左树的个数,就可以确定
        //左树节点的个数
        int leftCount = index - inStart;
        //找到中序遍历的root位置,左侧的就是左树,右侧的就是右树
        root.left = build(preorder, preStart + 1, preStart + leftCount,
                inorder, inStart, index - 1);
        root.right = build(preorder, preStart + leftCount + 1, preEnd,
                inorder, index + 1, inEnd);
        return root;
    }
}
